package com.jsaas.sys.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.JFinal;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.redis.Redis;
import com.jsaas.common.Constant;
import com.jsaas.model.Permission;
import com.jsaas.utils.MyUtils;
import com.jsaas.utils.ShiroUtils;

/**   
* @Title: PermissionService.java 
* @Package com.jsaas.sys.service 
* @Description: TODO(系统功能) 
* @author tuozq 
* @date 2017年12月15日 上午11:14:08 
* @version V1.0   
*/
public class PermissionService {
	
	private static final Log log = Log.getLog(PermissionService.class);
	
	public static final String all_enable_permission = "all_enable_permission";//所有已经启用的系统权限 
	
	/**
	 * 持久化jfinal构建的actionkey 
	 * 此方法需要在jfinal启动后调用
	 * @return
	 */
	public Ret generatorAtionKey(){
		List<String> actionkeys = JFinal.me().getAllActionKeys();
		List<Permission> list = Permission.dao.find("select * from " + Permission.table);
		List<String> allkeys = new ArrayList<String>();
		for (int i = 0,size = list.size(); i < size; i++) {
			allkeys.add(list.get(i).getActionKey());
		}
		
		List<Permission> addlist = new ArrayList<Permission>();
		String userId = ShiroUtils.getCurUser().getUserId();
		Date now = new Date();
		for (String key : actionkeys) {
			if(!allkeys.contains(key)){
				Permission info = new Permission();
				info.setActionKey(key);
				info.setEnable(true);
				info.setId(MyUtils.newId());
				info.setUpdateuserid(userId);
				info.setUpdatetime(now);
				info.setCreateuserid(userId);
				info.setCreatetime(now);
				addlist.add(info);
			}
		}
		
		Db.batchSave(addlist, 200);
		
		log.info("新增actionkey:" + addlist.size() +"条记录。");
		
		return Ret.ok().set("addsize", addlist.size());
	}
	
	/**
	 * 获取所有已启用的权限 （缓存）
	 * @return
	 */
	public static Map<String, Permission> getAllEnablePermission(){
		Map<String, Permission> rets = new HashMap<String, Permission>();
		List<Permission> list = Permission.dao.findByCache(Constant.COMMON_CACHE, all_enable_permission, "select * from " + Permission.table + " where enable = 1 order by action_key ");
		for (int i = 0,size = list.size(); i < size; i++) {
			Permission perm = list.get(i);
			rets.put(perm.getActionKey(), perm);
		}
		return rets;
	}
	
	/**
	 * 删除actionKey相关的cache
	 */
	public void clearCache(){
		Redis.use(Constant.COMMON_CACHE).del(all_enable_permission);
	}
	
	/**
	 * 保存
	 * @param model
	 * @return
	 */
	public Ret save(Permission model){
		if(model.getActionKey() == null){
			model.setActionKey("");
		}
		if(model.isExist("action_key", model.getActionKey())){
			return Ret.fail().set("msg", "功能url 不允许重复");
		}
		if(StrKit.notBlank(model.getPermission())){
			if(model.isExist("permission", model.getPermission())){
				return Ret.fail().set("msg", "权限标识 不允许重复");
			}
		}
		model.save();
		clearCache();
		return Ret.ok();
	}
	
	/**
	 * 删除权限
	 * @param id
	 * @return
	 */
	public Ret delete(String id){
		Permission.dao.deleteById(id);
		//删除角色绑定的权限
		SqlPara sqlPara = Db.getSqlPara("rolepermission.deleteByPermissionId", Kv.by("permissionId", id));
		Db.update(sqlPara);
		clearCache();
		return Ret.ok();
	}
	
}
